package nl.pcnerd.roelve.javagame.map;

import java.awt.Graphics;

import nl.pcnerd.roelve.javagame.Game;

public class MapLoader implements Runnable {

	// The current map to draw
	private Map currentMap;
	private int animCycle;

	public MapLoader() {
		animCycle = 0;
		currentMap = new Map();
		Thread animator = new Thread(this);
		animator.start();
	}

	/**
	 * Draws the map to the screen. Also draws the tiles based on animation.
	 * 
	 * @param g
	 *            the graphics object to draw to. Passed from Game
	 */
	public void drawBase(Graphics g) {
		for (Tile t : currentMap.getTileMap()) {
			if (t.isAnimated()) {
				g.drawImage(t.getTexture(animCycle,0), t.getX() * Game.TILE_SIZE,
						t.getY() * Game.TILE_SIZE, null);
			} else {
				g.drawImage(t.getTexture(1,0), t.getX() * Game.TILE_SIZE,
						t.getY() * Game.TILE_SIZE, null);
			}
		}
	}

	/**
	 * Two frame animation cycle shifts the subimage of the tile by one for
	 * animated tiles
	 */
	public void cycleAnim() {
		if (animCycle < 4)
			animCycle++;
		else
			animCycle = 0;
	}

	/**
	 * This method runs the animation cycle, currently only supports 4 frame
	 * animations, but could make more. Note that this also enforces 4 framed
	 * animations, so if you have an animated tile strip, it should contain 4
	 * subimages. TODO Fix this to make it more friendly
	 * 
	 */
	@Override
	public void run() {
		// TODO Auto-generated method stub
		boolean running = true;
		while (running) {
			try {
				// Simple animation based on thread, so mostly frame locked on
				// all clock speeds (not entirly sure)
				cycleAnim();
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
}
